package kk.orm.table;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import kk.orm.util.SQLBuilder;

// 注意不能跟ClassUtil、FieldUtil耦合
@SuppressWarnings("unused")
public class TableInfo {

	private String										className;
	private String										tableName;

	private static final HashMap<Class<?>, TableInfo>	tableInfoMap	= new HashMap<Class<?>, TableInfo>();

	/***
	 * @key property的表名，即Field的name <br>
	 * @value property实例，储存 数据表属性 与 类的Field对应信息
	 */
	public final HashMap<String, Property>				propertyMap		= new HashMap<String, Property>();

	/** 这个 数据表 是否建立 */
	private boolean										checkDatabese;

	private PrimaryKey									primaryKey;

	public static <T> TableInfo get(Class<T> clazz) {
		TableInfo tableInfo = tableInfoMap.get(clazz);

		if (tableInfo == null) {
			tableInfo = new TableInfo();

			tableInfo.className = clazz.getName();
			tableInfo.tableName = getTableName(clazz);

			// 向TableInfo加入所有Properties
			List<Property> pList = getPropertyList(clazz);
			for (Property p : pList) {
				tableInfo.propertyMap.put(p.getFieldName(), p);

				// 获取主键
				if (p.getField().getAnnotation(kk.orm.annotation.PrimaryKey.class) != null) {
					tableInfo.primaryKey = PrimaryKey.valueOf(p);
				}
			}

			// 从普通属性去除主键
			if (tableInfo.primaryKey != null)
				pList.remove(tableInfo.primaryKey);

			TableInfo.tableInfoMap.put(clazz, tableInfo);
		}

		return tableInfo;
	}

	public static List<Property> getPropertyList(Class<? extends Object> clazz) {
		List<Property> propertyList = new ArrayList<Property>();

		Field[] fields = getDeclaredFieldsJustReflect(clazz);
		for (Field field : fields) {

			Property property = new Property();
			property.setField(field);
			property.setFieldName(field.getName());
			property.setDataType(field.getType());

			propertyList.add(property);
		}

		return propertyList;
	}

	/** 根据类，获取 数据表 名称 */
	public static <T> String getTableName(Class<T> clazz) {
		String tableName = clazz.getName();
		tableName = tableName.replaceAll("\\.", "_");

		return tableName;
	}

	/**
	 * 纯利用发射，获取clazz及子类所有Fields
	 * 
	 * @param clazz
	 * @return
	 */
	private static Field[] getDeclaredFieldsJustReflect(Class<? extends Object> clazz) {
		List<Field> list = new ArrayList<Field>();

		Class<?> tClazz = clazz;

		while (!tClazz.equals(Object.class)) {
			list.addAll(Arrays.asList(tClazz.getDeclaredFields()));// 本层类的Field[]

			for (int j = 0; j < list.size(); j++) {
				Field field = list.get(j);

				field.setAccessible(true);
			}

			tClazz = tClazz.getSuperclass();
		}
		return list.toArray(new Field[0]);
	}

	public boolean isCheckDatabese() {
		return checkDatabese;
	}

	public void setCheckDatabese(boolean checkDatabese) {
		this.checkDatabese = checkDatabese;
	}
}
